package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;
import cn.wolfcode.wolf2w.util.AsserUtil;
import cn.wolfcode.wolf2w.util.IsPhone;
import cn.wolfcode.wolf2w.util.RedisKeys;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    private UserInfoRepository repository;

    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public UserInfo get(String id) {

        return repository.findById(id).orElse(null);
    }

    @Override
    public UserInfo findByPhone(String phone) {
        return repository.findByPhone(phone);
    }


    /**
     * 发送验证码
     */

    @Override
    public void sendVerifyCode(String phone) {

        // 生成4位数的注册验证码
        String code = UUID.randomUUID().toString().replace("-","").substring(0, 4);

        // 模拟 发送验证码到手机上
        StringBuilder sb = new StringBuilder();
        sb.append("你的验证码为").append(code).append("!  有效时间为5分钟");
        System.out.println(sb);

        // String sb = "【靓仔】你的验证码是：5873，3分钟内有效！";
        //sb.append("您的注册码为").append(code).append(",该验证码").append(Consts.VERIFY_CODE_VAI_TIME).append("分钟内有效");

//        RestTemplate template = new RestTemplate();
        // Url:https://way.jd.com/chuangxin/dxjk?mobile=13568813957&content=【靓仔】你的验证码是：5873，3分钟内有效！&appkey=d96c440472bffb0e214d1d7caa7bf2e4
//        String url = "https://way.jd.com/chuangxin/dxjk?mobile={1}&content={2}&appkey={3}";
//        String ret = template.getForObject(url, String.class, phone, sb, "d96c440472bffb0e214d1d7caa7bf2e4");

//        System.out.println(ret);
//        if (!ret.contains("Success")){
//            throw new LogicException("短信发送失败");
//        }

        // 将注册码缓存到redis中
        userInfoRedisService.setVerifyCode(phone,code);

    }

    /**
     * 校验注册信息以及验证码
     */
    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {

        // 对参数进行判空处理
        AsserUtil.isEmpty(phone,"手机号");
        AsserUtil.isEmpty(nickname,"用户名");
        AsserUtil.isEmpty(password,"密码");
        AsserUtil.isEmpty(rpassword,"确认密码");
        AsserUtil.isEmpty(verifyCode,"验证码");

        // 校验手机号码
        if (!IsPhone.isPhone(phone)){
            throw new LogicException("请输入有效的电话号码");
        }else if(findByPhone(phone) != null){
            throw new LogicException("您的号码已经注册");
        }

        UserInfo user = repository.findByNickname(nickname);
        if (user != null){
            throw new LogicException("用户名已存在");
        }

        // 密码等值校验
        if (!password.equals(rpassword)){
            throw new LogicException("两次密码不一致");
        }

        // 验证码校验
        String code = userInfoRedisService.getVerifyCode(phone);
        if (!verifyCode.equals(code)){
            throw new LogicException("请输入正确的验证码");
        }
        // 校验完成,根据用户输入的信息注册账号存入数据库
        UserInfo userInfo = new UserInfo();
        userInfo.setPhone(phone);
        userInfo.setNickname(nickname);
        userInfo.setPassword(password);
        repository.save(userInfo);
    }

    /**
     * 检查用户是否存在且密码是否正确
     * @param phone     手机号
     * @param password  密码
     * @return  UserInfo类型 user对象
     */
    @Override
    public UserInfo login(String phone, String password) {

        AsserUtil.isEmpty(phone,"手机号");
        AsserUtil.isEmpty(password,"密码");

        UserInfo user = repository.findByPhone(phone);
        if (!password.equals(user.getPassword())){
            throw  new LogicException("用户不存在或密码错误");
        }
        return user;
    }

    @Override
    public void update(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public List<String> getFavors(String sid, String userId) {

        String sidStr = redisTemplate.opsForValue().get(RedisKeys.USER_STRATEGY_FAVOR.join(userId));
        return JSON.parseObject(sidStr,ArrayList.class);
    }


}
